<template>
    <view style="margin: 20rpx">
        <form class="add-device" @submit="submit">
            <view class="add-device-item">
                <view class="add-device-item-title">{{ $t('General.add.deviceName') }}：</view>
                <input auto-focus type="text" :placeholder="$t('General.add.inputDeviceName')" name="deviceName" v-model="deviceName" class="add-device-control" style="padding: 20rpx" />
            </view>
            <view class="add-device-item">
                <view class="add-device-item-title">{{ $t('General.add.deviceType')  }}：</view>
                <picker mode="selector" @change="bindPickerChange" :range="deviceTypeList" range-key="deviceTypeName" class="add-device-control" style="padding: 0 20rpx">
                    <view style="width: 100%; height: 80rpx">
                        {{ deviceTypeName }}
                    </view>
                </picker>
            </view>
            <view class="form-item" style="padding: 0 20rpx">
                <button data-code="601604" data-eventName="click_scan_qrcode_add_dev" class="block" type="primary" form-type="submit">
                    {{ $t('General.add.confirm') }}</button>
            </view>
        </form>
    </view>
</template>

<script>
import {CodeMsg} from "@/utils/errorCode";
import {enCodeMsg} from "@/lang/en-code";

export default {
    data() {
        return {
            deviceNo: '',
            // 表单字段（设备编号）
            deviceName: '',
            // 表单字段（设备名称）
            deviceTypeList: [],
            // 设备类型列表
            deviceTypeName: '',
            // 页面上需要展示的字段（设备类型名称）
            pid: '' // productId
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        console.log('=== add-device-next:onLoad:', options);
        this.deviceNo = options.uuid
        this.getDeviceTypeListByPageForApp();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('=== add-device-next:onReady:');
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('=== add-device-next:onShow:');
        uni.setNavigationBarTitle({
            title: this.$t('General.home.jlink')
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('--- add-device-next:onHide:');
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        console.log('--- add-device-next:onUnload:');
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 分页查询设备类型
        getDeviceTypeListByPageForApp() {
            const data = {
                page: 1,
                limit: 999
            };
			// getDeviceTypeListByPageForApp
            getApp().globalData.api.getDeviceSortForDeviceType(data, (result) => {
                console.log('分页查询设备类型:', result);
                const deviceTypeList = result.data;
                deviceTypeList.pop()
                this.deviceTypeList = deviceTypeList
            });
        },

        // 选择picker
        bindPickerChange(ev) {
            console.log('选择picker:', ev);
            /**
       * 一个设备类型对象的属性列表
          connectMode: 1
          connectType: "0,1"
          connectUrl: "www.aaaa.com"
          description: "wifi基站"
          devicePic: "https://obs-xm-pub.obs.cn-south-1.myhuaweicloud.com//jvss/pic/1645171008111.jpg"
          deviceTypeName: "wifi基站"
          pid: "6"
       */

            const index = ev.detail.value;
            const deviceType = this.deviceTypeList[index];
			this.deviceTypeName = deviceType.deviceTypeName
			this.pid = deviceType.pid
        },
        isNull(str) {
			if (str == "") return true;
			var regu = "^[ ]+$";
			var re = new RegExp(regu);
			return re.test(str);
		},
        // 表单提交
        submit() {
            if (this.deviceName === '') {
                uni.showToast({
					icon:'none',
                    title: this.$t('General.add.addTips2')
                });
                return;
            }
			if ( this.isNull(this.deviceName) ) {
			    uni.showToast({
					icon:'none',
			        title: this.$t('General.add.addTips3')
			    });
			    return;
			}
			
			if (this.deviceName.length < 2 || this.deviceName.length > 50 ) {
			    uni.showToast({
					icon:'none',
			        title: this.$t('General.family.msg2')
			    });
			    return;
			}

            if (this.pid === '') {
                uni.showToast({
					icon:'none',
                    title: this.$t('General.add.addTips4')
                });
                return;
            }
            const data = {
                userGroupId: uni.getStorageSync('currentGroupId'),
                deviceNo: this.deviceNo,
                deviceName: this.deviceName,
                pid: this.pid,
                nickName: uni.getStorageSync('userInfo').nickName,
				timeZone:'Asia/Shanghai',
				devUserName:'admin'
            };
            getApp().globalData.api.addDevice(data, (result) => {
				let device = {
					deviceNo:this.deviceNo
				}
				result = result.data;
				console.log(result,'添加设备接口')
				if (result.code === 2000 || result.code === 200) {
					uni.showToast({
						title: this.$t('General.add.addTips5'),
						icon:'none',
						duration:2000,
						success: () => {
							setTimeout(()=>{
								uni.navigateTo({
									url: '/jvss/pagesDevice/device/room-select/room-select?type=2&device=' + encodeURIComponent(JSON.stringify(device))
								})
							},1000)
						}
					})
				} else {
					if(result.code === -91013){
						uni.showToast({
							title:this.$t('General.add.addTips6')+result.msg +this.$t('General.add.addTips7'),
							icon:'none',
							duration:2000
						})
					}else if(result.code === -91002) {
                        uni.showToast({
                            title:this.$t('General.add.addTips10'),
                            icon:'none',
                            duration:2000
                        })
                        uni.navigateBack({})

                    } else {
                        let lang = uni.getSystemInfoSync().language
						const toastMessage = (lang == 'zh-CN'? CodeMsg[result.code] :enCodeMsg[result.code]) || (result.msg.includes(
							'access token ??') ? this.$t('General.add.addTips8') : result.msg);
						uni.showToast({
							title: toastMessage,
							icon: 'none'
						});
					}
				}
				
                // uni.showModal({
                //     title: '提示',
                //     content: '设备添加成功！',
                //     cancelText: '再添设备',
                //     confirmText: '去首页',
                //     success: (res) => {
                //         if (res.confirm) {
                //             uni.reLaunch({
                //                 url: '/jvss/pages/device/home'
                //             });
                //         } else {
                //             uni.navigateBack({
                //                 delta: 1
                //             });
                //         }
                //     }
                // });
            },false,false);
        }
    }
};
</script>
<style>
.add-device {
    width: auto;
}

.add-device-item {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border-radius: 10rpx;
    margin-bottom: 20rpx;
    padding: 0 20rpx;
    line-height: 80rpx;
}

.add-device-item-title {
    font-size: 26rpx;
    color: #999999;
}

.add-device-control {
    background: #ffffff;
}
</style>
